<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

import { createRef, findTreeByKey, refs } from 'dsrz/utils'

import DsrzDownload from 'dsrz/svg/dsrz-download.vue'

import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'

import api from '@/request'

const { sms } = findTreeByKey(api, 'login')

defineOptions({
  name: 'LoginPage',
})

const {
  globalConfig: {
    title,
    login: { title: loginTitle, templateList },
  },
} = useAppStore()

const { Login } = useUserStore()

const params = reactive({
  username: 'yba188',
  password: 'Zjkm@123456',
  phone: '',
  code: '',
  captcha: '',
  grant_type: 'sms',
})

interface CaptchaResponse {
  data: {
    id: string
  }
}

const captcha = reactive({
  request: ({ data: { id } }: CaptchaResponse) => {
    const { phone } = params
    if (type.value === 'code-login') {
      countdown.timer = setInterval(() => {
        if (countdown.time > 0) {
          countdown.time--
        } else {
          countdown.time = 60
          clearInterval(countdown.timer)
        }
      }, 1000)
      return sms(
        { phone, captcha: id },
        {
          loading: { text: `发送验证码中...` },
          message: `发送成功`,
        },
      )
    } else {
      return Login(
        Object.assign(params, { captcha: id, grant_type: 'captcha' }),
      )
    }
  },
})

const type = ref('code-login')

const association = ref<string[]>(['qr-code-login', 'password-login'])

const countdown = reactive({
  time: 60,
  timer: undefined as number | undefined,
  start: () => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(params.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }
    refs.captchaRef?.open()
  },
})

const isCodeLogin = computed(() => type.value === 'code-login')

const isPasswordLogin = computed(() => type.value === 'password-login')

const isQRCodeLogin = computed(() => type.value === 'qr-code-login')

const handleLoginType = (list: string[], index: number) => {
  association.value =
    templateList.find(v => v.type === list[index])?.association || []
  type.value = list[index]
}

const handleLogin = () => {
  if (isCodeLogin.value) {
    if (!params.username || !params.captcha) {
      ElMessage.warning('请输入手机号和验证码')
      return
    }
  } else if (isPasswordLogin.value) {
    if (!params.username || !params.password) {
      ElMessage.warning('请输入账号和密码')
      return
    }
  }
  refs.captchaRef?.open()
}
</script>
<template>
  <div class="login">
    <header class="login__head">
      <section class="login__head__left">{{ title }}</section>
      <section class="login__head__right">
        <el-popover placement="bottom">
          <template #reference>
            <article>
              <DsrzDownload class="login__head__right--size" />
              手机店客户端下载
            </article>
          </template>
          <template #default>
            <img
              class="login__head__right__img"
              src="https://t10.baidu.com/it/app=25&f=JPEG&fm=175&fmt=auto&u=2576889072%2C379058380?w=400&h=400&s=3AA2208F6646514F041E0FF00300D036"
              alt="code"
            />
          </template>
        </el-popover>
      </section>
    </header>
    <div class="card">
      <main class="login__card">
        <header class="login__card__head">
          <span>{{ loginTitle }}</span>
        </header>
        <template v-for="v in templateList" :key="v.type">
          <section
            v-if="v.type === type"
            class="login__card__img"
            @click="handleLoginType(v.association, 0)"
          >
            <img :src="v.url" alt="logo" />
          </section>
        </template>
        <template v-if="isQRCodeLogin">
          <header class="login__card__title">请用51车商家端app登录</header>
          <section class="login__card__code">
            <img
              src="https://t10.baidu.com/it/app=25&f=JPEG&fm=175&fmt=auto&u=2576889072%2C379058380?w=400&h=400&s=3AA2208F6646514F041E0FF00300D036"
              alt="code"
            />
          </section>
        </template>
        <template v-else>
          <template v-if="isCodeLogin">
            <section class="login__card__item">
              <header>手机号</header>
              <el-input
                v-model="params.username"
                placeholder="请输入手机号"
                clearable
              />
            </section>
            <section class="login__card__item">
              <header>验证码</header>
              <el-input
                v-model="params.password"
                placeholder="请输入验证码"
                clearable
                style="background-color: #e8e8e8; border-radius: 10px"
              >
                <template #append>
                  <span v-if="countdown.time === 60" @click="countdown.start">
                    发送验证码
                  </span>
                  <span v-else>{{ countdown.time }}s</span>
                </template>
              </el-input>
            </section>
          </template>
          <template v-if="isPasswordLogin">
            <section class="login__card__item">
              <header>账号</header>
              <el-input
                v-model="params.username"
                placeholder="请输入账号"
                clearable
              />
            </section>
            <section class="login__card__item mt-20">
              <header>密码</header>
              <el-input
                v-model="params.password"
                type="password"
                placeholder="请输入密码"
                clearable
              />
            </section>
          </template>
          <section class="login__card__btn">
            <el-button
              class="login__card__btn--size"
              type="primary"
              @click="handleLogin"
            >
              登录
            </el-button>
          </section>
          <footer
            v-if="templateList.length > 0"
            class="login__card__foot"
            @click="handleLoginType(association, 1)"
          >
            切换登录方式
          </footer>
        </template>
      </main>
      <CurrencyCaptcha
        :ref="(e: any) => createRef(e, 'captchaRef')"
        :request="captcha.request"
      />
    </div>
  </div>
</template>
<style scoped lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/login-bg.jpg') no-repeat;
  background-size: 100vw 100vh;
  position: relative;
  &__head {
    display: flex;
    justify-content: space-between;
    z-index: 2;
    width: 100%;
    padding: 30px;
    box-sizing: border-box;
    position: absolute;
    left: 0;
    top: 0;
    // background-color: #ffffff;
    // box-shadow: 0 0 10px 2px rgba(2, 2, 2, 0.1);
    &__left {
      font-size: 20px;
    }
    &__right {
      cursor: pointer;
      &--size {
        width: 20px;
        transform: translate(-2px, 4px);
      }
      &__img {
        width: 120px;
        margin: auto;
        display: block;
      }
    }
  }
  .card {
    height: 100%;
    position: absolute;
    right: 30px;
    padding-top: 27vh;
    box-sizing: border-box;
  }
  &__card {
    z-index: 1;
    width: 360px;
    // height: 40vh;
    background-color: #ffffff;
    box-shadow: 0 0 10px 2px rgba(2, 2, 2, 0.1);
    margin: auto;
    border-radius: 10px;
    padding: 40px 30px;
    box-sizing: border-box;
    position: relative;
    &__head {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    &__img {
      width: 0px;
      height: 0px;
      border-width: 50px 0 0 50px;
      border-style: solid;
      border-color: var(--el-color-primary) transparent transparent transparent;
      border-radius: 0 10px 0 0;
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
      img {
        position: absolute;
        width: 40px;
        height: 40px;
        right: 2px;
        top: -50px;
      }
    }
    &__item {
      width: 100%;
      font-size: 14px;
      header {
        margin-bottom: 10px;
      }
      ::v-deep(.el-input) {
        --el-input-height: 44px;
        --el-input-bg-color: #e8e8e8;
        --el-input-border-color: #e8e8e8;
        --el-input-border-radius: 10px;
        --el-fill-color-light: #e8e8e8;
        --el-color-info: var(--el-color-primary);
        --el-input-hover-border-color: #e8e8e8;
        --el-input-focus-border-color: #e8e8e8;
        margin-bottom: 20px;
      }
      ::v-deep(.el-input-group__append) {
        cursor: pointer;
      }
    }
    &__title {
      text-align: center;
      font-size: 14px;
    }
    &__code {
      margin-top: 10px;
      text-align: center;
      img {
        width: 200px;
        height: 200px;
      }
    }
    &__btn {
      margin-top: 60px;
      &--size {
        width: 100%;
        height: 46px;
        border-radius: 6px;
        font-size: 18px;
      }
    }
    &__foot {
      margin-top: 10px;
      font-size: 14px;
      color: var(--el-color-primary);
      text-align: right;
      cursor: pointer;
    }
  }
}
</style>
